//
//  ScanView.m
//  TengyunStation
//
//  Created by Johnny on 15/8/24.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ScanView.h"
#import <AVFoundation/AVFoundation.h>
#import "TSHeader.h"
#import "DSToast.h"
#import "ZBarSDK.h"

@interface ScanView ()<ZBarReaderViewDelegate> {
    ZBarReaderView *_readerView;
}

@end

@implementation ScanView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self awakeFromNib];
    }
    return self;
}

- (void)awakeFromNib {
    //监听应用进入活跃状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    self.codeList = [NSMutableArray arrayWithCapacity:1];
    _isDownScroll = YES;
    float height = self.frame.size.height - 20;
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width - 284)/2.0, 10, 284, height)];
    bgImageView.image = [[UIImage imageNamed:@"saos_box"] stretchableImageWithLeftCapWidth:140 topCapHeight:50];
    [self addSubview:bgImageView];
    _lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width - 284)/2.0, (self.frame.size.height - 2)/2.0, 284, 2)];
    UIImage *lineImage = [UIImage imageNamed:@"saos_box_line"];
    UIImage *strethLineImage = [lineImage stretchableImageWithLeftCapWidth:160 topCapHeight:3];
    _lineImageView.image = strethLineImage;
    _lineImageView.hidden = YES;
    [self addSubview:_lineImageView];
    _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityView.center = self.center;
    [_activityView startAnimating];
    [self addSubview:_activityView];
    [self performSelector:@selector(setZBarSDK) withObject:nil afterDelay:0.5];
}

- (void)setZBarSDK {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    _readerView = [[ZBarReaderView alloc] init];
    _readerView.device = device;
    _readerView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    _readerView.readerDelegate = self;
    _readerView.tracksSymbols = NO;
//    _readerView.enableCache = NO;
    //关闭闪光灯
    _readerView.torchMode = 0;
    [self insertSubview:_readerView atIndex:0];
    [_readerView start];
    _lineImageView.hidden = NO;
    [_activityView stopAnimating];
    _activityView.hidden = YES;
}

- (void)lineUpOrDownScroll {
    float y = _lineImageView.frame.origin.y;
    if (_isDownScroll) {
        y += 1.5;
        if (y >= self.frame.size.height - 15) {
            _isDownScroll = NO;
        }
    } else {
        y -= 1.5;
        if (y <= 15) {
            _isDownScroll = YES;
        }
    }
    _lineImageView.frame = CGRectMake(_lineImageView.frame.origin.x, y, _lineImageView.frame.size.width, _lineImageView.frame.size.height);
}

//通知
- (void)didBecomActive {
    [_readerView start];
}

#pragma mark ZBarReaderViewDelegate
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image {
    for (ZBarSymbol *symbol in symbols) {
        if ([symbol.data hasPrefix:@"http"]) {
            [DSToast showText:@"请扫描正确的运单条码" InView:self];
        } else if ([self.codeList containsObject:symbol.data]) {
            [DSToast showText:@"该运单已接收，请重新扫描。" InView:self];
        } else {
            if ([_delegate respondsToSelector:@selector(didFinishScanCode:)]) {
                [_delegate didFinishScanCode:symbol.data];
            }
        }
        break;
    }
}

- (void)stopScanning {
    [_timer invalidate];
    _lineImageView.hidden = YES;
    _readerView.readerDelegate = nil;
}

- (void)startScanning {
    _lineImageView.hidden = NO;
    _readerView.readerDelegate = self;
    if (![_timer isValid]) {
        _timer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:0.02 target:self selector:@selector(lineUpOrDownScroll) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

- (void)dealloc {
    _lineImageView = nil;
    _timer = nil;
    _delegate = nil;
    _readerView.device = nil;
    _readerView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

@end
